﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Yuans.BinaryConfig.BlobIO
{
    public class PlainHexTextBlobValueIO : BlobValueIO
    {
        public byte[] BlobValue { set; get; }
        public static byte[] ParseLineToBlob(string stringLine)
        {
            string[] splitStringUnit = stringLine.Split(new string[] { "  ", "   ", " ", "," },
                                             StringSplitOptions.RemoveEmptyEntries);

            byte[] rawBytes = new byte[splitStringUnit.Length];

            for (int i = 0; i < rawBytes.Length; i++)
            {
                rawBytes[i] = byte.Parse(splitStringUnit[i], System.Globalization.NumberStyles.HexNumber);
            }

            return rawBytes;
        }
        public void ImportFile(string fileName)
        {
            List<byte> blobList = new List<byte>();
            byte[] lineRawBytes;
            try
            {
                // Create an instance of StreamReader to read from a file. 
                // The using statement also closes the StreamReader. 
                using (StreamReader fileReader = new StreamReader(fileName))
                {
                    string line;
                    // Read and display lines from the file until the end of  
                    // the file is reached. 
                    while ((line = fileReader.ReadLine()) != null)
                    {
                        lineRawBytes = ParseLineToBlob(line);
                        if (lineRawBytes != null)
                        {
                            blobList.AddRange(lineRawBytes);
                        }
                    }
                }
                BlobValue = blobList.ToArray();
            }
            catch (Exception e)
            {

            }
        }
        public PlainHexTextBlobValueIO(string fileName)
        {
            ImportFile(fileName);
        }
        public void ExportFile(string fileName)
        {
            File.WriteAllBytes(fileName, BlobValue);
        }
    }
}
